package com.ft.controller;

import com.ft.domain.Post;
import com.ft.service.IPostService;
import com.ft.utils.Code;
import com.ft.utils.Result;
import com.ft.utils.SnowFlakeGenerateIdWorker;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author: ft
 * @Date: 2023/01/11/19:49
 * @Description:
 */
@RestController
@RequestMapping("/post")
@CrossOrigin
public class PostController {
    @Autowired
    private IPostService postService;
    @PostMapping("")
    public Result addpost(@RequestBody Post post) throws IllegalAccessException {
        //创建帖子编号
        SnowFlakeGenerateIdWorker snowFlakeGenerateIdWorker =
                new SnowFlakeGenerateIdWorker(0L,0L);
        String id = snowFlakeGenerateIdWorker.generateNextId();
        //设置帖子编号
        post.setId (Long.valueOf (id));
        int i = postService.addPost (post);
        if(i== 1){
            return new Result(Code.POST_OK,post,"增加帖子成功!");
        }else {
            return new Result(Code.POST_ERR,"创建帖子失败!");
        }
    }

    /**
     * 获取分页数据
     * @return
     */
    @GetMapping("/{type}/{page}")
    public Result getpost(@PathVariable int type,@PathVariable int page){
        List order = postService.getPostList(type,page);
        return new Result(Code.GET_OK,order,"获取成功");
    }
    @PutMapping ("/praise/{praise}/{number}/{id}")
    public Result updatePraise(@PathVariable String praise ,@PathVariable int number,@PathVariable Long id){
        //点赞数据为空的情况
        if(praise.equals ("aaa")){
            praise = "";
        }
        int i = postService.addPraiseAndNumber (praise, number, id);
        if(i == 1){
            return new Result(Code.PUT_OK,"点赞成功!");
        }
        return new Result(Code.PUT_ERR,"点赞失败");
    }
    /**
     * 帖子搜索内容
     * @param content
     * @return
     */
    @GetMapping("/search/{content}/{type}/{page}")
    public Result getOrderBySearch(@PathVariable String content,@PathVariable int type, @PathVariable int page){
        List search = postService.search (content,type,page);
        return new Result(Code.GET_OK,search,"获取成功");
    }
    //获取帖子点赞用户id
    @GetMapping("/commentNum/{id}")
    public Result getPostcommentNum(@PathVariable Long id){
        String postcommentNum = postService.getPostcommentNum (id);
        return new Result(Code.GET_OK,postcommentNum,"获取成功");
    }
    @DeleteMapping("/{id}")
    public Result deletePostById(@PathVariable Long id){
        int i = postService.deletePost (id);
        if(i == 1){
            return new Result(Code.DELETE_OK,"删除成功");
        }
        return new Result(Code.DELETE_ERR,"删除失败");
    }
}
